﻿@using ABC.Controllers.ViewModels
@using ABC.Controllers.ViewModels.My
@using ABC.Core.Extentions
@model MyNewClientViewModel
@{
    ViewBag.Title = "Новый клиент - Азбука24";
    Layout = "~/Views/Shared/_MyLayout.cshtml";
}
<div class="row-fluid">
    <!--// Левая колонка -->
    @{Html.RenderPartial("_SectionClientsMenu", new BaseViewModel());}
    <script type="text/javascript">
    $(function () {
      @* $("#avatarUpload").uploadify({
            uploader: '@Url.Action("ChangeClientAvatar", "Upload")',
            cancelImg: '@Url.VirtualImageUrl("uploadify-cancel.png")',
            swf: '@Url.VirtualScriptUrl("uploadify.swf")',
            formData: { userId: $("#newclient").val() },
            auto: true,
            fileObjName: 'fileUpload',
            hideButton: false,
            fileTypeExts: '*.jpg;*.png;',
            multi: false,
            method: "post",
            fileTypeDesc: 'Файлы изображений *.jpg;*.png;',
            width: '94',
            height: '18',
            buttonText: "Изменить фото",
            onUploadError: function (file, errorCode, errorMsg, errorString) {
                alert('Файл ' + file.name + ' не был загружен: ' + errorMsg);
            },
            onUploadSuccess: function (file, data, response) {
                if (data == "no") {
                    alert("Необходимо зарегестрировать клиента");
                }
                else {
                    $("#avatar").attr("src", data);
                }
            }

        });
        $(".uploadify").addClass("btn");
        $(".swfupload").css("width", "100px").css("left", "10px");
        $("#avatarUpload-queue").hide();
        *@
        function addField(forLabel, forDiv, nameField, afterIns) {
            var field = "<div class='control-group'><label class='control-label' for='" + nameField + "'>" + forLabel + "</label><div class='controls'>" +
            forDiv + "</div></div>";
            afterIns.after(field);
            $(".phone").mask("+7 (999) 999-99-99");
        };
        function addFieldToForm(eventObject) {
            var f = $("#form1 .control-group");
            switch ($(eventObject.target).text()) {
                case "Отчество":
                    f.eq(2).removeClass("hide");
                    $(eventObject.target).parent("li").replaceWith("");
                    break;
                case "Пол":
                    f.eq(3).removeClass("hide");
                    $(eventObject.target).parent("li").replaceWith("");
                    break;
                case "Компания":
                    f.eq(4).removeClass("hide");
                    $(eventObject.target).parent("li").replaceWith("");
                    if (f.eq(5).hasClass("hide") && f.eq(6).hasClass("hide")) {
                            f.eq(3).after("<hr>");
                        }
                    break;
                case "Должность":
                    f.eq(5).removeClass("hide");
                    $(eventObject.target).parent("li").replaceWith("");
                    if (f.eq(4).hasClass("hide") && f.eq(6).hasClass("hide")) {
                            f.eq(3).after("<hr>");
                        }
                    break;
                case "Отдел":
                    f.eq(6).removeClass("hide");
                    $(eventObject.target).parent("li").replaceWith("");
                    if (f.eq(4).hasClass("hide") && f.eq(5).hasClass("hide")) {
                            f.eq(3).after("<hr>");
                        }
                    break;
                case "Телефон":
                    var countPhone = $("select[name='PhoneType']").length;
                    var phrase = $("select[name='PhoneType']:last").next("p");
                    $("select[name='PhoneType']:last").next("p").replaceWith("");
                    addField("Телефон", "<input id='PhoneValue" + countPhone + "' class='input-large phone' type='tel' name='PhoneValue" +
                             countPhone + "'/> <select class='input-medium' name='PhoneType'><option value='Мобильный'>Мобильный</option><option value='Рабочий'>Рабочий</option><option value='Домашний'>Домашний</option></select>",
                             "PhoneValue" + countPhone, $("select[name='PhoneType']:last").parents(".control-group"));
                    $("select[name='PhoneType']:last").after(phrase.wrap("<p>"));
                    break;
                case "Электронная почта":
                    var countEmail = $("select[name='EmailType']").length;
                    addField("Электронная почта", "<input id='EmailValue" + countEmail + "' class='input-large' type='email'name='EmailValue" + countEmail +
                             "' /> <select class='input-medium' name='EmailType'> <option value='Личная'>Личная</option><option value='Рабочая'>Рабочая</option></select>",
                             "EmailValue" + countEmail, $("select[name='EmailType']:last").parents(".control-group"));
                    break;
                case "IM":
                    if ($("#ImValue0").parents(".control-group").hasClass("hide")) {
                        $("#ImValue0").parents(".control-group").removeClass("hide");
                    } else {
                        var countIm = $("select[name='ImType']").length;
                        addField("IM", "<input id='ImValue" + countIm + "' class='input-large' type='text' name='ImValue" + countIm +
                        "' /> <select class='input-medium' name='ImType'><option value='Icq'>ICQ</option><option value='Jabber'>Jabber</option><option value='Skype'>Skype</option></select>",
                        "ImValue" + countIm, $("select[name='ImType']:last").parents(".control-group"));
                    }
                    break;
                case "Соцсеть":
                    if ($("#SocNetValue0").parents(".control-group").hasClass("hide")) {
                        $("#SocNetValue0").parents(".control-group").removeClass("hide");
                    } else {
                        var countSocNet = $("select[name='SocNetType']").length;
                        addField("Соцсеть", "<input id='SocNetValue" + countSocNet + "' class='input-large' type='text' name='SocNetValue" + countSocNet +
                        "'/> <select class='input-medium' name='SocNetType'><option value='Вконтакте'>Вконтакте</option><option value='Одноклассники'>Одноклассники</option><option value='МойМир'>Мой Мир</option><option value='Facebook'>Facebook</option><option value='MySpace'>MySpace</option></select>",
                        "SocNetValue" + countSocNet, $("select[name='SocNetType']:last").parents(".control-group"));
                    }
                    break;
                case "Адрес":
                    var countAddress = $("select[name='AddressType']").length;
                    addField("Адрес", "<textarea id='AddressValue" + countAddress + "' class='input-large' rows='3' placeholder = 'Город, улица, дом ' name='AddressValue" + countAddress +
                        "'></textarea> <select class='input-medium' name='AddressType'><option value='Личный'>Личный</option><option value='Рабочий'>Рабочий</option></select>" + 
                        "<span class='help-block'><a data-toggle='modal' href='#map-select'><i class='icon-map-marker'></i>Указать на карте</a></span>",
                        "AddressValue" + countAddress, $("select[name='AddressType']:last").parents(".control-group"));
                    break;
                case "Дата получения прав":
                    $("#DateLawToCar").parents(".control-group").removeClass("hide");
                    $(eventObject.target).parent("li").replaceWith("");
                    $("#isExperience").val("False");
                    break;
                default: break;
            }
            if ($("#addField ul.dropdown-menu li").eq(0).hasClass("divider")) {
                $("#addField ul.dropdown-menu li").eq(0).replaceWith("");
            }
            if ($("#addField ul.dropdown-menu li:last").hasClass("divider")) {
                $("#addField ul.dropdown-menu li:last").replaceWith("");
            }
        }

        $(".span9 ul.dropdown-menu li a").click(addFieldToForm);
        
        if ($("select[name='PhoneType']").length > 1) {
           for (var i = 0; i < $("select[name='PhoneType']").length - 1; i++) {
                $("select[name='PhoneType']").eq(i).next("p").replaceWith("");
           }
        }
        if ($("#BirthDay").val()) {
             CalcAge();
        }
    });  
    
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#avatar').attr("src", "@Url.VirtualImageUrl("avatar.gif")");
                    $('#avatar')
                        .attr('src', e.target.result);                    
                    $('#avatar').css("max-height", "290px");
                    $('#avatar').css("max-width", "250px");
                   
                };
                reader.readAsDataURL(input.files[0]);               
            }
        };

        function DateFocus(ddd){
            if ($(ddd).val()=="") {
                var today = new Date();
                today.setFullYear(Math.ceil(today.getFullYear() - 18));
                var todayFormat = ((String(today.getDate()).length == 1) ? "0" + today.getDate() : today.getDate()) + "." + ((String(today.getMonth() + 1).length == 1) ? "0" + Math.ceil(today.getMonth() + 1) : Math.ceil(today.getMonth() + 1)) + "." + ((String(today.getFullYear()).length == 1) ? "0" + today.getFullYear() : today.getFullYear());
                $(ddd).val(todayFormat);
            }
        }
        
    function DeleteAvatar() {
        if ($("#Id").val()) {
            $.ajax({
            url: '@Url.Action("DeleteClientAvatar", "Upload")',
            type: "POST",
            data: { userId: $("#Id").val() },
            success: function (data) {
            }
        });
        }
        $('#avatar').attr("src", '@Url.VirtualImageUrl("avatar.gif")');
        $("#avatarUpload").replaceWith("<input type='file' onchange='readURL(this);' class='hide' name='avatarUpload' id='avatarUpload' />");
    }
    var age = 0;
    function CalcExperience() {
        $.ajax({
            url: '@Url.Action("CalcExperience", "Clients")',
            type: "POST",
            data: { datetime: $("#DateLawToCar").val(), ageClient: age },
            success: function (data) {
                if (data == "error" || !data) {
                    $("#experience").html("Неверно введена дата");
                    $("#DateLawToCar").val("");
                    $("#isExperience").val("False");
                }
            else {
                    data = $.parseJSON(data);
                    $("#experience").html("стаж " + data.FullAge + " " + data.Additional);
                    $("#experience-digit").val(data.FullAge);
                    $("#isExperience").val("True");
                }
            }
        });
    }
    function CalcAge() {
        $.ajax({
            url: '@Url.Action("CalcAge", "Clients")',
            type: "POST",
            data: { datetime: $("#BirthDay").val() },
            success: function (data) {
                if($("#DateLawToCar").parents(".control-group").hasClass("hide")) {
                    $("#isExperience").val("True");
                }
                else {
                    $("#isExperience").val("False");
                }
                if (data == "error" || !data) {
                    $("#age").html("Неверно введена дата");
                }
                else {
                    data = $.parseJSON(data);
                    $("#age").html("возраст " + data.FullAge + " " + data.Additional);
                    $("#age-digit").val(data.FullAge);
                    age = data.FullAge;
                }
                if (age <= 18) {
                    $("#DateLawToCar").attr("disabled", "disabled");
                    $("#DateLawToCar").val("");
                    $("#experience").html("");
                    $("#isExperience").val("True");
                }
                else {
                    $("#DateLawToCar").removeAttr("disabled");
                    if ($("#DateLawToCar").val()) {
                        CalcExperience();
                    }
                }

            }
        });
    }
    </script>
    <!--// Правая колонка -->
    <div class="span9">
        <div class="page-header">
            <h2>
                @(string.IsNullOrEmpty(Model.NewClientId) ? "Новый клиент" : String.Format("Редактирование {0} {1}", Model.LastName, Model.FirstName))</h2>
        </div>
        <div class="row-fluid">
            <div class="span8">
                @using (Html.BeginForm("Add", "Clients", FormMethod.Post, new { @class = "form-horizontal", id = "form1", enctype = "multipart/form-data" }))
                {
                    <input type="file" class="hide" accept="image/jpeg" onchange="readURL(this);" name="avatarUpload" id="avatarUpload" />
                    if (Model.ErrorName)
                    {
                    <div class="alert alert-error fade in">
                        <button class="close" data-dismiss="alert">
                            ×</button>
                        <strong>Ошибка!</strong>
                        <ul class="unstyled">
                            <li>Не введено значение в обязательное поле "Имя".</li>
                        </ul>
                    </div>
                    }
                    if (Model.WarningEmail)
                    {
                    <div class="alert alert-block">
                        <a class="close" data-dismiss="alert" href="#">×</a>
                        <h4 class="alert-heading">
                            Предупреждение!</h4>
                        <ul class="unstyled">
                            <li>Значение в поле E-mail не соответствует формату. Доставка писем работать не будет!</li>
                        </ul>
                    </div>
                    }
                    <fieldset>
                        @Html.HiddenFor(x => x.NewClientId)
                        <div class="@(Model.ErrorName ? "control-group error" : "control-group")">
                            <label class="control-label" for="name">
                                Имя</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.FirstName, new { @class = "input-large", id = "name" })
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label" for="surname">
                                Фамилия</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.LastName, new { @class = "input-large", id = "surname" })
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.MiddleName) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="patronymic">
                                Отчество</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.MiddleName, new { @class = "input-large", id = "patronymic" })
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.Sex) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="sex">
                                Пол</label>
                            <div class="controls">
                                <label class="radio inline">
                                    @Html.RadioButtonFor(x => x.Sex, "Мужчина")
                                    Мужчина
                                </label>
                                <label class="radio inline">
                                    @Html.RadioButtonFor(x => x.Sex, "Женщина")
                                    Женщина
                                </label>
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.Company) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="company">
                                Компания</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.Company, new { @class = "input-large", id = "company" })
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.Post) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="post">
                                Должность</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.Post, new { @class = "input-large", id = "post" })
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.Department) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="department">
                                Отдел</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.Department, new { @class = "input-large", id = "department" })
                            </div>
                        </div>
                        <hr>
                        @foreach (var phone in Model.ListPhones)
                        {
                            <div class="control-group">
                                <label class="control-label" for="@phone.NameField">
                                    Телефон</label>
                                <div class="controls">
                                    @Html.TextBox(phone.NameField, phone.Value, new { @class = "input-large phone", type = "tel", id = phone.NameField })
                                    @Html.DropDownListFor(x => x.PhoneType, phone.ItemList, new { @class = "input-medium" })
                                    <p class="help-block">
                                        Реальный номер клиента <a href="#">видите только вы.</a></p>
                                </div>
                            </div>
                        }
                        @foreach (var email in Model.ListEmails)
                        {
                            <div class="control-group">
                                <label class="control-label" for="@email.NameField">
                                    Электронная почта</label>
                                <div class="controls">
                                    @Html.TextBox(email.NameField, email.Value, new { @class = "input-large", type = "email", id = email.NameField })
                                    @Html.DropDownListFor(x => x.EmailType, email.ItemList, new { @class = "input-medium" })
                                </div>
                            </div>
                        }
                        @foreach (var im in Model.ListIm)
                        {
                            <div class="@(string.IsNullOrEmpty(im.Value) ? "control-group hide" : "control-group")">
                                <label class="control-label" for="@im.NameField">
                                    IM</label>
                                <div class="controls">
                                    @Html.TextBox(im.NameField, im.Value, new { @class = "input-large", id = im.NameField })
                                    @Html.DropDownList("ImType", im.ItemList, new { @class = "input-medium" })
                                </div>
                            </div>
                        }
                        @foreach (var socnet in Model.ListSocNetworks)
                        {
                            <div class="@(string.IsNullOrEmpty(socnet.Value) ? "control-group hide" : "control-group")">
                                <label class="control-label" for="@socnet.NameField">
                                    Соцсеть</label>
                                <div class="controls">
                                    @Html.TextBox(socnet.NameField, socnet.Value, new { @class = "input-large", id = socnet.NameField })
                                    @Html.DropDownList("SocNetType", socnet.ItemList, new { @class = "input-medium" })
                                </div>
                            </div>
                        }
                        @foreach (var address in Model.ListAddresses)
                        {
                            <div class="control-group">
                                <label class="control-label" for="@address.NameField">
                                    Адрес</label>
                                <div class="controls">
                                    @Html.TextArea(address.NameField, address.Value, new { @class = "input-large", id = address.NameField, placeholder = "Город, улица, дом ", rows = "3" })
                                    @Html.DropDownListFor(x => x.AddressType, address.ItemList, new { @class = "input-medium" })
                                    <span class="help-block"><a data-toggle="modal" href="#map-select"><i class="icon-map-marker">
                                    </i>Указать на карте</a></span>
                                </div>
                            </div>
                        }
                        <div class="control-group">
                            <label class="control-label" for="BirthDay">
                                Дата рождения</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.BirthDay, new { @class = "input-small date", id = "BirthDay", onblur = "CalcAge();", onmousedown = "DateFocus(this);" })
                                <span id="age" class="help-inline"></span>
                                @Html.Hidden("age-digit")
                            </div>
                        </div>
                        <div class="@(Model.DateLawToCar == DateTime.MinValue.ToString("dd.MM.yyyy") || string.IsNullOrEmpty(Model.DateLawToCar) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="DateLawToCar">
                                Дата получения прав</label>
                            <div class="controls">
                                @Html.Hidden("isExperience", true, new { id = "isExperience" })
                                @Html.TextBoxFor(x => x.DateLawToCar, new { @class = "input-small date", id = "DateLawToCar", onblur = "CalcExperience();" })
                                <span id="experience" class="help-inline"></span>
                                @Html.Hidden("experience-digit")
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label" for="notes">
                                Заметки</label>
                            <div class="controls">
                                @Html.TextAreaFor(x => x.Notes, new { @class = "input-large", id = "notes", rows = "3" })
                            </div>
                        </div>
                    </fieldset>
                    <div class="control-group">
                        <div class="controls">
                            <div id="addField" class="btn-group dropup">
                                <button class="btn dropdown-toggle" data-toggle="dropdown">
                                    Добавить поле <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu">
                                    @if (string.IsNullOrEmpty(Model.MiddleName))
                                    {
                                        <li><a href="javascript:void(0)">Отчество</a></li>
                                        <li class="divider"></li>
                                    }
                                    @if (string.IsNullOrEmpty(Model.Company))
                                    {
                                        <li><a href="javascript:void(0)">Компания</a></li>
                                    }
                                    @if (string.IsNullOrEmpty(Model.Post))
                                    {
                                        <li><a href="javascript:void(0)">Должность</a></li>
                                    }
                                    @if (string.IsNullOrEmpty(Model.Department))
                                    {

                                        <li><a href="javascript:void(0)">Отдел</a></li>
                                    }
                                    @if (string.IsNullOrEmpty(Model.Department) || string.IsNullOrEmpty(Model.Post) || string.IsNullOrEmpty(Model.Company))
                                    {
                                        <li class="divider"></li>
                                    }
                                    <li><a href="javascript:void(0)">Телефон</a></li>
                                    <li><a href="javascript:void(0)">Электронная почта</a></li>
                                    <li><a href="javascript:void(0)">IM</a></li>
                                    <li><a href="javascript:void(0)">Соцсеть</a></li>
                                    <li><a href="javascript:void(0)">Адрес</a></li>
                                    @if (Model.DateLawToCar == DateTime.MinValue.ToString("dd.MM.yyyy") || string.IsNullOrEmpty(Model.DateLawToCar))
                                    {
                                        <li class="divider"></li>
                                        <li><a href="javascript:void(0)">Дата получения прав</a></li>
                                    }
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="form-actions">
                        <button class="btn btn-primary btn-large" onclick="$('#form1').submit();" href="javascript:void(0)">
                            Сохранить и продолжить</button>
                    </div>
                }
            </div>
            <div class="span4">
                <div class="thumbnail">
                    <img src="@(string.IsNullOrEmpty(Model.Avatar) || Model.Avatar.Equals("0") ? @Url.VirtualImageUrl("avatar.gif") : Url.Image(Model.Avatar, 250, 290))" id="avatar" alt="">
                    <div class="caption">
                        <div class="btn-group">
                            <button type="button" class="btn " onclick="$('#avatarUpload').click()">
                                Изменить фото</button>
                            <button class="btn" rel="tooltip" type="button" title="Удалить фотографию" onclick="DeleteAvatar();">
                                <i class="icon-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!--// Модальное окно выбора адреса доставки -->
<div class="modal hide " id="map-select">
    <div class="modal-header">
        <button data-dismiss="modal" class="close">
            ×</button>
        <h3>
            Выбор адреса</h3>
    </div>
    <div class="modal-body">
        <iframe width="100%" height="350" frameborder="0" scrolling="no" marginheight="0"
            marginwidth="0" src="https://maps.google.com/?ie=UTF8&amp;ll=55.746342,37.621136&amp;spn=0.060678,0.154324&amp;t=m&amp;z=13&amp;output=embed">
        </iframe>
    </div>
    <div class="modal-footer">
        <span class="pull-left">Адрес: Москва, Большая Семеновская, 40с13</span>
        <button class="btn btn-primary">
            Выбрать адрес</button>
        <!--button data-dismiss="modal" class="btn">Закрыть окно</button-->
    </div>
</div>
<!-- Модальное окно выбора адреса доставки //-->
